//
//  CHReachability.m
//  bridging_js
//
//  Created by cyptt on 2021/9/7.
//

#import "CHReachability.h"

@interface CHReachability ()
@property (nonatomic) CHBaseReachability *internetReachability;
@property(nonatomic,copy)void(^successB)(NetworkStatus );
@end

@implementation CHReachability


- (instancetype)init
{
    self = [super init];
    if (self) {
   
        self.internetReachability = [CHBaseReachability reachabilityForInternetConnection];
    }
    return self;
}





-(NetworkStatus)currentReachabilityStatus{
    
    //当前网络状态
    NetworkStatus networkStatus = [self.internetReachability currentReachabilityStatus];

    NSLog(@"当前状态%ld",(long)networkStatus);
    return  networkStatus;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [self.internetReachability stopNotifier];
   
}

-(void)removeNetworkListener{
    [self.internetReachability stopNotifier];

   [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
    self.internetReachability = nil;


  
}
-(void)checkNeatStatus:(void(^)(NetworkStatus))netStatusB;{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    self.successB = netStatusB;
    [self.internetReachability startNotifier];
//    [self updateInterfaceWithReachability:self.internetReachability];
}

/*!
 * Called by Reachability whenever status changes.
 */
- (void) reachabilityChanged:(NSNotification *)note
{
    CHBaseReachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[CHBaseReachability class]]);
    [self updateInterfaceWithReachability:curReach];
}

- (void)updateInterfaceWithReachability:(CHBaseReachability *)reachability
{
    NetworkStatus netStatus = [reachability currentReachabilityStatus];
//    BOOL connectionRequired = [reachability connectionRequired];
    
    switch (netStatus)
    {
        case NotReachable:        {
            NSLog(@"Access Not Available");
            if(self.successB){
                self.successB(NotReachable);
            }
            break;
        }

        case ReachableViaWWAN:        {
            NSLog(@"Reachable WWAN");
            if(self.successB){
                self.successB(ReachableViaWWAN);
            }
            break;
        }
        case ReachableViaWiFi:        {
            if(self.successB){
                self.successB(ReachableViaWiFi);
            }
            NSLog(@"Reachable WiFi");
            break;
        }
    }
    
}
@end
